package com.blb.thread;

/**
 * 两个线程交替输出ABAB....
 */
public class PrintDemo {

    public synchronized void printA(){
        while (true){
            System.out.println("A");
            //通知其它线程执行
            this.notify();
            //当前线程等待
            try {
                Thread.sleep(1000);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void printB(){
        while (true){
            System.out.println("B");
            //通知其它线程执行
            this.notify();
            //当前线程等待
            try {
                Thread.sleep(1000);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        PrintDemo demo = new PrintDemo();
        new Thread(() -> {
            demo.printA();
        }).start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            demo.printB();
        }).start();
    }
}
